#!/usr/bin/python3
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-

import os
import subprocess
from gi.repository import GLib
from fm_param import FmConst
from usr_session_common import UsrSessionHelperBase, WayFireInstance


class UsrSessionHelperVnc(UsrSessionHelperBase):

    def __init__(self, parent, session_id, **kwargs):
        super().__init__(parent, session_id)

        self._tmpDir = FmConst.getTmpDir(self._sessionId)

        self._wayfireObj = None
        self._wayvncProc = None

    def start(self, machine):
        envDict = os.environ.copy()

        self._wayfireObj = WayFireInstance(self._sessionId, os.path.join(self._tmpDir, "wayfire.ini"), machine, "fcitx", "pipewire", True)
        assert all([x not in os.environ for x in self._wayfireObj.envDict])
        envDict.update(self._wayfireObj.envDict)

        command = ["wayvnc"]
        self._wayvncProc = subprocess.Popen(command)
        GLib.child_watch_add(self._wayvncProc.pid, self._callback)

    def exit(self):
        if self._wayvncProc is not None:
            self._wayvncProc.terminate()
            self._wayvncProc = None
        if self._wayfireObj is not None:
            self._wayfireObj.dispose()
            self._wayfireObj = None

    def _callback(self, pid, status):
        GLib.spawn_check_wait_status(status)
